package controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import model.Goods;
import model.Manager;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import service.IGoodsService;
import util.DateUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @aythor:侯仪澳
 * @data:2022/7/21
 */
@Controller
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;

    //查询所有的货物信息
    @RequestMapping("queryAllGoods")
    public ModelAndView queryAllGoods(Goods goods) {
        ModelAndView modelAndView = new ModelAndView();
        List<Goods> list = goodsService.queryAllGoods(goods);
        modelAndView.addObject("list", list);
        modelAndView.setViewName("manager/goods_list");
        return modelAndView;
    }

    //查询所有上架货物的信息，   状态值为1的货物
    @RequestMapping("queryUpGoods")
    public ModelAndView queryUpGoods(Goods goods,Integer pageNo) {
        goods.setgStatus(1);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("goods", goods);//保留name值
        List<Goods> first = goodsService.queryFirstSort(null);
        modelAndView.addObject("first",  first);//一级分类
        List<Goods> second = goodsService.querySecondSort(goods);
        modelAndView.addObject("second",  second);//二级分类
        Map<String,Object> map = goodsService.queryGoodsByStatus(goods,pageNo);
        modelAndView.addObject("list",  map.get("list"));//将数据传到前端
        modelAndView.addObject("pageNo", map.get("pageNo"));
        modelAndView.addObject("totalPage", map.get("totalPage"));
        modelAndView.addObject("gStatus", goods.getgStatus());
        modelAndView.setViewName("manager/goods_list");
        return modelAndView;
    }

    //查询所有下架货物的信息，   状态值为0的货物
    @RequestMapping("queryDownGoods")
    public ModelAndView queryDownGoods(Goods goods,Integer pageNo,Integer totalPage1) {
        goods.setgStatus(0);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("goods", goods);//保留值
        List<Goods> first = goodsService.queryFirstSort(null);
        modelAndView.addObject("first",  first);//一级分类
        List<Goods> second = goodsService.querySecondSort(goods);
        modelAndView.addObject("second",  second);//二级分类
        Map<String,Object> map = goodsService.queryGoodsByStatus(goods,pageNo);
        modelAndView.addObject("list",  map.get("list"));//将数据传到前端
        modelAndView.addObject("pageNo", map.get("pageNo"));
        modelAndView.addObject("totalPage", map.get("totalPage"));
        modelAndView.addObject("gStatus", goods.getgStatus());
        modelAndView.setViewName("manager/goods_list");
        return modelAndView;
    }

    //跳转添加货物页面
    @RequestMapping("addGoodsPage")
    public ModelAndView addGoodsPage(){
        ModelAndView modelAndView = new ModelAndView();
        List<Goods> first = goodsService.queryFirstSort(null);
        modelAndView.addObject("first",  first);//一级分类
        List<Goods> second = goodsService.querySecondSort(null);
        modelAndView.addObject("second",  second);//二级分类
        modelAndView.setViewName("manager/goods_add");
        return modelAndView;
    }

    //跳转修改货物页面
    @RequestMapping("updateGoodsPage")
    public ModelAndView updateGoodsPage(Goods goods){
        ModelAndView modelAndView = new ModelAndView();
        List<Goods> list = goodsService.queryAllGoods(goods);
        modelAndView.addObject("goods",list.get(0));
        List<Goods> first = goodsService.queryFirstSort(null);
        modelAndView.addObject("first",  first);//一级分类
        goods.setParentId(list.get(0).getParentId());
        List<Goods> second = goodsService.querySecondSort(goods);
        modelAndView.addObject("second",  second);//二级分类
        modelAndView.setViewName("manager/goods_update");
        return modelAndView;
    }

    //添加一个货物
    @RequestMapping("addOneGoods")
    @ResponseBody
    public String addOneGoods(Goods goods){
        return goodsService.addOneGoods(goods);
    }

    //一键上架货物
    @RequestMapping("UpGoods")
    @ResponseBody
    public String UpGoods(@RequestParam(value = "ids[]") List<Integer> list){
        List<Goods> list1 = new ArrayList<>();
        //将前端传入的集合取出放入实体类中（再加入状态值），再放入新的集合中
        for (int i = 0;i < list.size();i++){
            list1.add(new Goods(list.get(i),0));
        }
        return goodsService.updateGoodsBatch(list1);
    }

    //一键下架货物
    @RequestMapping("DownGoods")
    @ResponseBody
    public String DownGoods(@RequestParam(value = "ids[]") List<Integer> list){
        List<Goods> list1 = new ArrayList<>();
        //将前端传入的集合取出放入实体类中（再加入状态值），再放入新的集合中
        for (int i = 0;i < list.size();i++){
            list1.add(new Goods(list.get(i),1));
        }
        return goodsService.updateGoodsBatch(list1);
    }

    //修改一个货物信息
    @RequestMapping("updateOneGoods")
    @ResponseBody
    public String updateOneGoods(Goods goods){
        return goodsService.updateOneGoods(goods);
    }

    //实现二级联动
    @RequestMapping(value = "querySecond",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String querySecond(Goods goods){
        List<Goods> list  = goodsService.querySecondSort(goods);
        //创建json数组
        JSONArray arr = new JSONArray();
        for (Goods goods1 : list) {
            //创建json对象
            JSONObject obj = new JSONObject();
            //添加键值对
            obj.put("id", goods1.getId());
            obj.put("name", goods1.getsName());
            arr.add(obj);
        }
        return arr.toJSONString();
    }

    //上传图片
    @RequestMapping("/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile imgFile) throws IOException {
        //@RequestParam用于将指定名称的请求参数赋值给方法中的形参
        String contentType = imgFile.getContentType();//IMAGE/PNG
        System.out.println(contentType);

        String name = imgFile.getName();
        System.out.println(name);

        String originalName = imgFile.getOriginalFilename();
        System.out.println(originalName);

        long size = imgFile.getSize();
        System.out.println(size);

        InputStream in = null;
        OutputStream out = null;
        //文件目的地址
        String filePath = "E:/img/";

        File file = new File(filePath);
        if(!file.exists()){
            //2、如果不存在，则创建目录
            file.mkdir();
            //mkdir()方法只能创建一层目录
            //mkdirs()该方法可以根据路径，递归创建多层目录
        }
        try{
            //根据源文件获取输入流
            in = imgFile.getInputStream();
            //生成目标文件名
            filePath += DateUtil.dateFormat()+".png";
            //创建文件输出流
            out = new FileOutputStream(new File(filePath));
            //读取输入流，将读取的字节写入到数据流并刷新输出流
            IOUtils.copy(in, out);
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (in != null){
                in.close();
            }
            if (out != null){
                out.close();
            }
        }
        JSONObject json = new JSONObject();
        json.put("code", 1);
        json.put("imgUrl", filePath);
        return json.toJSONString();
    }
}
